package com.bsh.shiro;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;

import com.bsh.utils.PageJosnMessage;
import com.google.gson.Gson;

/**
 * common exception resolver
 * @author gsh
 *
 */
public class SysExceptionResolver extends ExceptionHandlerExceptionResolver {
	static Gson gson = new Gson();
	@Override
	protected ModelAndView doResolveHandlerMethodException(HttpServletRequest request, HttpServletResponse response,
			HandlerMethod handlerMethod, Exception ex) {

		Method method = handlerMethod.getMethod();

		if (method == null) {
			return null;
		}

		PageJosnMessage msg = new PageJosnMessage("400", ex.getMessage());
		msg.putData("method", method.getName());

		ModelAndView mv = super.doResolveHandlerMethodException(request, response, handlerMethod, ex);
		ResponseBody responseBodyAnn = AnnotationUtils.findAnnotation(method, ResponseBody.class);
		if (responseBodyAnn != null) {			
			String json = gson.toJson(msg);
			try {
				response.getWriter().write(json);
				response.flushBuffer();
				return null;
			} catch (IOException e) {
			}

		} else {
			if (mv != null)
				return mv;
			else {
				mv = new ModelAndView("/error/unResoledErr");
				mv.addObject("_ERR", msg);
			}
		}

		return mv;
	}

}
